package com.lzy.libreoffice.autoconfiguration.service.impl;

import com.lzy.libreoffice.autoconfiguration.service.LibreofficeService;
import org.jodconverter.core.office.OfficeManager;
import org.jodconverter.local.JodConverter;
import org.jodconverter.local.office.LocalOfficeManager;

import java.io.File;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * description: LibreofficeService (Libreoffice管理)<br>
 * date: 2022-9-28 23:26 <br>
 * author: lcc <br>
 * version: 1.0 <br>
 */
public class LibreofficeServiceImpl implements LibreofficeService {

    @Override
    public void startLibreOffice(String path,String port) {
        try {
            System.out.println(path);
            System.out.println(port);
            System.out.println("LibreOffice启动中......");
            List<Integer> port_list = new ArrayList<>();
            for (String s : port.split(",")) {
                port_list.add(Integer.parseInt(s));
            }

            if (port_list.size() > 0) {
                int[] intArray = new int[port_list.size()];
                for (int i = 0; i < port_list.size(); i++) {
                    intArray[i] = port_list.get(i);
                }
                OfficeManager manager =
                        LocalOfficeManager.builder()
                                .officeHome(path)
                                .portNumbers(intArray)
                                .taskExecutionTimeout(5 * 60 * 1000L)
                                .taskQueueTimeout(1000 * 1000 * 60 * 24L).install().build();
                manager.start();
                System.out.println("LibreOffice启动成功");
            }
        }catch (Exception e){
            System.out.println("LibreOffice启动失败");
            e.printStackTrace();
        }
    }

    @Override
    public void office2Pdf(String sourceFile, String destFile) throws Exception {
        try {
            File office = new File(sourceFile);
            String name = office.getName();
            String fileType = office.getName().substring(name.lastIndexOf("."), name.length());
            String[] office_type = {".doc", ".docx", ".xls", ".xlsx", ".ppt", ".pptx"};
            if (Arrays.asList(office_type).contains(fileType.toLowerCase())){
                JodConverter.convert(new File(sourceFile)).to(new File(destFile)).execute();
            }else {
                throw new Exception("必须是office文件【\".doc\", \".docx\", \".xls\", \".xlsx\", \".ppt\", \".pptx\"】");
            }
        } catch (Exception e) {
            throw e;
        }
    }
}
